<?php
namespace app\admin\model;
use think\Model;
class Admin extends Model
{
    //新增
    public function addadmin($data){
        //传递过来的数据不能为空或者是一个数组类型
        if(empty($data) || !is_array($data)){
            return false;
        }
        if($data['password']){
            $data['password'] = md5($data['password']);
        }
        $adminData = array();
        $adminData['username'] = $data['username'];
        $adminData['password'] = $data['password'];
        if($this->save($adminData)){
            $groupAccess['uid'] = $this->id;
            $groupAccess['group_id'] = $data['group_id'];
            db('auth_group_access')->insert($groupAccess);
            return true;
        }else{
            return false;
        }
    }

    //查询
    public function getadmin(){
        return $this::paginate(2,false,[
            //需要使用自定义分页的时候，去thinkphp/library/think/paginator/driver目录下，新建一个和type同名的文件，首字母大写
            'type'=>'boot',
            'var_page' => 'page',
        ]);
    }

    //修改
    public function saveadmin($data,$admins){
        if(!$data['username']){
            return 2;//管理员用户名为空
        }
        if(!$data['password']){
            $data['password'] = $admins['password'];
        }else{
            $data['password'] = md5($data['password']);
        }
        db('auth_group_access')->where(array('uid'=>$data['id']))->update(['group_id'=>$data['group_id']]);
        return $this::update(['username'=>$data['username'],'password'=>$data['password']],['id'=>$data['id']]);
    }

    //删除
    public function deladmin($id){
        if($this::destroy($id)){
            return 1;
        }else{
            return 2;
        }
    }

    //登录
    public function login($data){
        $admin = $this::get(['username' => $data['username']]);
        if($admin){
            if($admin['password'] == md5($data['password'])){
                session('uid', $admin['id']);
                session('username', $admin['username']);
                return 2; //登录密码正确的情况
            }else{
                return 3; //登录密码错误
            }
        }else{
            return 1; //用户不存在的情况
        }
    }
}
